<template>
	<view class="page-container" scroll-y="true">
		<uni-nav-bar dark :fixed="true" status-bar :border="false" title="新航向教育" />
		<view class="work">
			<text class="title">培训课程</text>
		</view>
		<view class="top">
		  <view class="search">
		    <text class="icon-search iconfont"></text>
		    <input 
				class="searchInput"
				type="text" 
				v-model="searchName" 
				confirm-hold 
				placeholder="搜索培训课程" 
				@input="inputTxt"
				placeholder-class='placeholder' 
			/>
		  </view>
		</view>
		<view class="item-wrap" v-if='recommendList && recommendList.length'>
			<view
				v-for= "(item,index) in recommendList"
				:key='index'
				class="work-item" 
				hover-class="active" 
				@tap="goDetail(item)"
			>
				<view class="content">
					<view class="item-title">
					  <view>{{item.courseTitle}}</view>
					  <text>{{item.cost}}</text>
					</view>
					<view class="describe">
					  <text>{{item.classification ? item.classification : '暂无'}}</text>
					  <text>{{item.time ? item.time : '暂无'}}</text>
					  <!-- <text>未融资</text> -->
					</view>
					<view class="place ellipsis" v-html='item.briefIntroduction'>
						<!-- {{item.briefIntroduction}} -->
					</view>
				</view>
			</view>
			<!-- 加载提示 -->
			<view :class="more?'loader':'noMore'">
				<view>{{more?'':'没有更多了~'}}</view>
			</view>
		</view>
		<view v-else class="noData">暂无数据</view>
	</view>
</template>

<script>
	import workItem from '@/components/workItem.vue';
	import gridItem from '@/components/gridItem.vue';
	import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
	export default {
		data() {
			return {		
				recommendList:[], // 列表数据
				currentPage:1, // 当前分页
				pageSize:10, // 分页条数
				total:0, // 总条数
				loadStatus:"more", // 加载状态
				searchName: '', // 搜索名称
				timer: null // 定时器
			}
		},
		onLoad(options) {
			this.initRecommendList();
		},
		onShow(){
			uni.hideKeyboard();
			this.user_token = uni.getStorageSync('user_token');
		},
		components:{
			workItem,
			gridItem
		},
		methods: {
			...mapMutations(['setStoreAccessToken']),
			
			// 推荐-查看全部
			viewMore(){
				uni.switchTab({
					url: "/pages/job/job",
				})
			},
			// 实时搜索培训课程
			inputTxt(e) {
				// 需要防抖处理的函数
				if(this.timer) {
					clearTimeout(this.timer);
				}
				this.timer = setTimeout(()=>{
					this.searchName = e.target.value;
					this.currentPage = 1;
					this.initRecommendList();
					this.timer = null
				},1000)
			},
			// 获取推荐列表
			async initRecommendList(){
				const _this = this;
				try{
					const res = await this.$api.trainingList({
						page:this.currentPage,
						name: this.searchName ? this.searchName : '',
						pageSize: this.pageSize,
						typeId: ''
					});
					if(res.code == 200){
						const regex = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
						this.total = res.data.totalCount;
						if (this.currentPage == 1) {
							this.recommendList = res.data.rows;
							this.recommendList.map(async item => {
								let replacedString = await this.replaceAsync(item.briefIntroduction, regex, this.getNewImgPath);
								replacedString = replacedString.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
								item.briefIntroduction = replacedString;
								return item;
							});
							if (this.recommendList.length < this.total) {
								this.loadStatus = "more";
							} else {
								this.loadStatus = "no-more";
							}
						} else {
							this.loadStatus = "loading";
							setTimeout(()=>{
								this.recommendList = this.recommendList.concat(res.data.rows);
								this.recommendList.map(async item => {
									let replacedString = await this.replaceAsync(item.briefIntroduction, regex, this.getNewImgPath);
									replacedString = replacedString.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
									item.briefIntroduction = replacedString;
									return item;
								})
								if (this.recommendList.length < this.total) {
									this.loadStatus = "more";
								} else {
									this.loadStatus = "no-more";
								}
							},1000)
						}
						
						uni.hideNavigationBarLoading();
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
					
				}catch(e){
					//TODO handle the exception
				}
				
			},
			// 获取新图片地址
			// getNewImgPath(path) {
			// 	let newImgPath = path.replace('h2w-1256690844.cos.ap-beijing.myqcloud.com','cdn.h2w.sm6.top');
			// 	return new Promise(async (resolve,reject) => {
			// 		try{
			// 			const res = await this.$api.getImgPath(newImgPath);
			// 			if(res.code == 200) {
			// 				resolve(res.data);
			// 			}
			// 		}catch(e){
			// 			//TODO handle the exception
			// 			reject(e);
			// 		}
			// 	})
			// },
			 // 获取图片地址
			getNewImgPath(url) {
			  let newUrl = url.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
				let imgPath = capture.split('?')[0];
				return imgPath;
			  })
			  return new Promise(async (resolve, reject) =>{
				try {
				  const res = await await this.$api.getImgPath(newUrl);
				  if(res.code == 200) {
					resolve(res.data);
				  } 
				} catch (error) {
				  console.log('error', error);
				  reject(error);
				}
			  })
			},
			// 替换函数
			async replaceAsync(str, regex, asyncFn) {
			  const promises = [];
			  str.replace(regex, (match, ...args) => {
				  const promise = asyncFn(match, ...args);
				  promises.push(promise);
			  });
			  const data = await Promise.all(promises);
			  return str.replace(regex, () => '<img src="'+ data.shift() + '"/>');
			},
			// 查看是否是新用户
			getLogin() {
				let that = this;
				wx.login({
					success: res => {
						this.code = res.code;
						if (this.code) {
							let params = {
								code: this.code
							}
							this.$api.get_ready_auth(params).then(res => {
								if (res.code === 200) {
									uni.removeStorageSync('user_token');
									uni.setStorageSync('user_token', res.data.accessToken);
									uni.navigateTo({
										// 保留当前页面，跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
										url: "/pages/training/trainingDetail?id=" + item.id,
									})
								} else {
									uni.showModal({
										title: '温馨提示',
										content: '请先授权登录',
										confirmText: '同意',
										cancelText: '关闭',
										success: function(res) {
											if (res.confirm) {
												uni.navigateTo({
													// 保留当前页面，跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
													url: "/pages/auth/auth"
												})
											} else if (res.cancel) {
												console.log('关闭');
											}
										}
									});
								}
							})
						}
					}
				})
			},
			// 推荐-查看详情
			goDetail(item){
				if(this.user_token){
					uni.navigateTo({
						// 保留当前页面，跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
						url: "/pages/training/trainingDetail?id=" + item.id,
					})
				}else{
					this.getLogin()
				}
			},
		},
		
		// 上拉加载
		onReachBottom() {
			this.currentPage++;
			if (this.recommendList.length < this.total) {
				this.initRecommendList();
			} else {
				uni.hideNavigationBarLoading();
				this.loadStatus = "no-more";
			}
		},
		
		// 下拉刷新
		onPullDownRefresh(){
			this.loadStatus = "more";
			this.currentPage = 1;
			this.pageSize = 10;
			this.total = 0;
			this.searchName = '';
			this.initRecommendList();
			setTimeout(function () {
				uni.stopPullDownRefresh();  //停止下拉刷新动画
			}, 1000);
		},
	}
</script>

<style lang="scss" scoped>
 page {
   width: 680rpx;
   // 84
   // padding: 0 35rpx 180rpx;
   padding-bottom: 180rpx;
 }

  .top {
		width: 680rpx;
		height: 80rpx;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		padding-top: 30rpx;
		background: var(--white);
		// background: $uni-primary;

		.search {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			width: 666rpx;
			padding-left: 16rpx;
			border-radius: 10rpx;
			background: $uni-bg-color;
			height: 80rpx;
			color: #AAAAAA;
			line-height: 80rpx;
			font-size: 34rpx;
			
			// left: -104rpx;
			z-index: 2;
			.icon-search {
				margin-right: 20rpx;
			}
		}
  }
  .item-wrap{
	  width: 680rpx;
	  margin: auto;
	  background: #fff;
	  margin-top: 20rpx;
  }
  .work-item {
    // width: 680rpx;
    padding: 30rpx 35rpx;
    margin: auto;
    background: $uni-bg-color;
    margin-bottom: 20rpx;
	border-radius: 5px;
  
    .item-title {
      display: flex;
      justify-content: space-between;
      font-weight: bold;
  
      view {
        font-size: 34rpx;
      }
  
      text {
        font-size: 30rpx;
        color: $uni-primary;
      }
    }
	.content{
		// padding: 15rpx 20rpx;
		margin: auto;
		background: $uni-bg-color;
		margin-bottom: 10rpx;
		
		.item-title {
		  display: flex;
		  justify-content: space-between;
		  font-weight: bold;
		
		  view {
		    font-size: 34rpx;
		  }
		
		  text {
		    font-size: 30rpx;
		    color: $uni-primary;
		  }
		}
		
		.describe {
		  margin-top: 8rpx;
		
		  text {
		    margin-right: 20rpx;
		    font-size: 28rpx;
		    // color: $uni-text-color-grey;
		    color: #333;
		  }
		}
		.place {
			flex: 1;
			// color: $uni-text-color-grey;
			color: #333;
			font-size: 24rpx;
			text-align: left;
			letter-spacing: 1px;
		}
		p img {           //------------解决  在v-heml="xxxx.xxx"外面添加个div  设置大小
			width: 100% !important;  //--------------------设置大小  添加!important
			height: auto !important;
		}
		.ellipsis{
			text-overflow: -o-ellipsis-lastline;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			line-clamp: 2;
			-webkit-box-orient: vertical;
		}
		
	}
  }
  
  .work {
    width: 680rpx;
	margin: auto;
	background: #fff;
    .title {
		width: 680rpx;
		height: 100rpx;
		margin: auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid $uni-bg-color-grey;
		font-size: 42rpx;
		font-weight: bold;
    }
  }

  .loader {
    background: #fff;
    padding: 30rpx 0;
    view {
      border: 10rpx solid #fff;
      border-top: 10rpx solid $uni-color-primary;
      border-right: 10rpx solid #91DAD3;
      border-bottom: 10rpx solid #B0EBE5;
      border-left: 10rpx solid #E2F7F0;
      border-radius: 50%;
      width: 40rpx;
      height: 40rpx;
      animation: spin .8s linear infinite;
      margin: auto;
    }
  }
  .noMore {
    color: $uni-text-color-grey;
    background: #fff;
    padding: 30rpx 0;
    font-size: 28rpx;
    text-align: center;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
</style>

